<script setup lang="ts">
import {onMounted, ref, watch} from "vue";
import {NotificationOutlined} from '@ant-design/icons-vue'

const props = defineProps({
  startTime: {
    type: String,
    default: '',
    required: true
  },
  endTime: {
    type: String,
    default: '',
    required: true
  },
  endText: {
    type: String,
    default: '活动已结束'
  },
  startText: {
    type: String,
    default: '优惠活动未开始'
  },
});

const flag = ref(0)
const dTime = ref('00')
const hTime = ref('00')
const mTime = ref('00')
const sTime = ref('00')
let timer: any = null;

onMounted(() => {
  countDown(props.startTime, props.endTime)
})

watch(() => props.endTime, (newEndTime) => {
  clearInterval(timer);
  countDown(props.startTime, newEndTime);
});

function countDown(startTimestamp: any, timestamp: any) {
  timer = setInterval(function () {
    let nowTime = new Date();
    let endTime = new Date(timestamp * 1000);
    let startTime = new Date(startTimestamp * 1000);
    let t = endTime.getTime() - nowTime.getTime();
    let t2 = startTime.getTime() - nowTime.getTime();
    // 活动未开始
    if (t2 > 0) {
      flag.value = -1;
      clearInterval(timer);
      return
    }

    // 活动开始
    if (t > 0) {
      flag.value = 0;
      let day: any = Math.floor(t / 86400000);
      let hour: any = Math.floor((t / 3600000) % 24);
      let min: any = Math.floor((t / 60000) % 60);
      let sec: any = Math.floor((t / 1000) % 60);
      hour = hour < 10 ? "0" + hour : hour;
      min = min < 10 ? "0" + min : min;
      sec = sec < 10 ? "0" + sec : sec;
      dTime.value = day;
      hTime.value = hour;
      mTime.value = min;
      sTime.value = sec;
    } else {
      // 活动结束
      flag.value = 1;
      clearInterval(timer);
    }
  }, 1000);
}
</script>

<template>
	<span>
		<slot>
      <span>
        <span v-if="flag==0">
          <NotificationOutlined/>
          限时优惠仅剩
          <span class="text-red-500 font-bold">{{ dTime }}</span> 天
          <span class="text-red-500 font-bold">{{ hTime }}</span> 小时
          <span class="text-red-500 font-bold">{{ mTime }}</span> 分
          <span class="text-red-500 font-bold">{{ sTime }}</span> 秒
        </span>
        <span v-if="flag==-1" class="text-blue-500 font-bold">
          <NotificationOutlined/>
          {{ startText }}
        </span>
        <span v-if="flag==1" class="text-red-500 font-bold">
          <NotificationOutlined/>
          {{ endText }}
        </span>
      </span>
    </slot>
	</span>
</template>

<style scoped lang="less">

</style>
